package com.mbigger.admin.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mbigger.admin.common.RequestHolder;
import com.mbigger.admin.dao.RoleUserMapper;
import com.mbigger.admin.dao.UserMapper;
import com.mbigger.admin.entity.RoleUser;
import com.mbigger.admin.entity.User;
import com.mbigger.admin.service.RoleUserService;
import com.mbigger.admin.util.IpUtil;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class RoleUserServiceImpl implements RoleUserService{

	@Autowired
	private RoleUserMapper roleUserMapper;
	@Autowired
	private UserMapper userMapper;

	public List<User> getListByRoleId(int roleId) {
		List<Integer> userIdList = roleUserMapper.getUserIdListByRoleId(roleId);
		if (CollectionUtils.isEmpty(userIdList)) {
			return Lists.newArrayList();
		}
		return userMapper.getByIdList(userIdList);
	}

	public void changeRoleUsers(int roleId, List<Integer> userIdList) {
		List<Integer> originUserIdList = roleUserMapper.getUserIdListByRoleId(roleId);
		if (originUserIdList.size() == userIdList.size()) {
			Set<Integer> originUserIdSet = Sets.newHashSet(originUserIdList);
			Set<Integer> userIdSet = Sets.newHashSet(userIdList);
			originUserIdSet.removeAll(userIdSet);
			if (CollectionUtils.isEmpty(originUserIdSet)) {
				return;
			}
		}
		updateRoleUsers(roleId, userIdList);
	}

	@Transactional
	private void updateRoleUsers(int roleId, List<Integer> userIdList) {
		roleUserMapper.deleteByRoleId(roleId);

		if (CollectionUtils.isEmpty(userIdList)) {
			return;
		}
		List<RoleUser> roleUserList = Lists.newArrayList();
		for (Integer userId : userIdList) {
			RoleUser roleUser = RoleUser.builder().roleId(roleId).userId(userId)
					.operator(RequestHolder.getCurrentUser().getUsername())
					.operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new Date()).build();
			roleUserList.add(roleUser);
		}
		roleUserMapper.batchInsert(roleUserList);
	}
}
